package com.huaxin.hxcloud.activity;


import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.DeviceImgDTO;
import com.huaxin.common.Entity.ImageInfo;
import com.huaxin.common.Entity.StationImgDTO;
import com.huaxin.common.Global;
import com.huaxin.common.media.ImageGalleryActivity;
import com.huaxin.common.media.SelectImageActivity;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tools.Log;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.utils.Util;
import com.huaxin.common.view.pulltorefresh.extras.recyclerview.PullToRefreshRecyclerView;
import com.huaxin.hxcloud.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by Administrator on 2016/9/21.
 */
public class ImageActivity extends BaseActivity implements SelectImageActivity.Callback {


    private static final int IMAGE_SIZE = 4;
    @BindView(R.id.more)
    ImageView                 more;
    @BindView(R.id.toolbar)
    Toolbar                   toolbar;
    @BindView(R.id.pull_view)

    PullToRefreshRecyclerView pullView;
    private MyAdapter adapter;
    private List dataList = new ArrayList<>();
    private RecyclerView gridView;

    public final static int TYPE_STATION = 0x00;
    public final static int TYPE_DEVICE  = 0x01;
    private             int _type        = 0;
    private String                 _code;
    private String                 _title;
    private HxSationDialogFragment mDialogFrament;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_station_img;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    public static void showDeviceImg(Context context, String deviceCode) {
        Intent intent = new Intent(context, ImageActivity.class);
        intent.putExtra(Constants.IK_TYPE, TYPE_DEVICE);
        intent.putExtra(Constants.IK_DEVICE_CODE, deviceCode);
        context.startActivity(intent);

    }

    public static void showStationImg(Context context, String stationCode) {
        Intent intent = new Intent(context, ImageActivity.class);
        intent.putExtra(Constants.IK_TYPE, TYPE_STATION);
        intent.putExtra(Constants.IK_STATION_CODE, stationCode);
        context.startActivity(intent);

    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        if (extras.containsKey(Constants.IK_TYPE)) {
            _type = extras.getInt(Constants.IK_TYPE, 0);
            if (_type == TYPE_DEVICE) {
                _code = extras.getString(Constants.IK_DEVICE_CODE);
                _title = "设备图片";
            } else {
                _code = extras.getString(Constants.IK_STATION_CODE);
                _title = "站点图片";
            }
        } else {
            Log.d("Zoes", "no stationCode");
        }
    }

    @Override
    public void requestData() {
        ApiRequestData(LOADING);
    }

    @Override
    public void initView() {
        setSupportActionBar(toolbar);
        toolbar.setTitle(_title);
        more.setImageResource(R.drawable.icon_camera);

        gridView = pullView.getRefreshableView();
        gridView.setLayoutManager(new GridLayoutManager(this, 3));

        adapter = new MyAdapter();
        gridView.setAdapter(adapter);
    }


    @OnClick({R.id.more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.more:
                SelectImageActivity.selectImages(this, IMAGE_SIZE, true, null, this);
                break;
            default:
                break;
        }

    }

    @Override
    public void doSelectDone(final String[] images, final String[] compress) {
        mDialogFrament = HxSationDialogFragment.newInstance();
        mDialogFrament.show(getFragmentManager(), "image");
        mDialogFrament.setImgList(images, compress);
        mDialogFrament.setMaxSize(IMAGE_SIZE);
        mDialogFrament.setLoadLisetener(new HxSationDialogFragment.UpLoadLisetener() {
            @Override
            public void upload() {
                String[] imgs = mDialogFrament.getImgs();
                if (imgs.length == 0) {
                    ToastUtil.showToast("至少一张照片");
                } else if (Util.checkNull(mDialogFrament.getDes())) {
                    ToastUtil.showToast("备注不能为空");
                } else {
                    ApiUploadImg(imgs);
                }
            }
        });
     /*commitDialog = new CommitDialog(this);
        commitDialog.setImgList(images, compress);

        commitDialog.setTitle("上传图片");
        commitDialog.setMaxSize(IMAGE_SIZE);
        commitDialog.setOnCommitListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String[] imgs = commitDialog.getImgs();
                if (imgs.length == 0) {
                    ToastUtil.showToast("至少一张照片");
                } else if (Util.checkNull(commitDialog.getDes())) {
                    ToastUtil.showToast("备注不能为空");
                } else {
                    ApiUploadImg(imgs);
                }
            }

        });*/
        //commitDialog.show();
    }

    private void ApiUploadImg(String[] imgs) {
        Call<BaseDTO> call;
        if (_type == TYPE_STATION) {
            call = HxTransmitRequestHelper.getRequestApi().uploadStationImg(_code, RequestHelper.createFileParts(imgs),
                    mDialogFrament
                            .getDes());
        } else {
            call = HxTransmitRequestHelper.getRequestApi().uploadDeviceImg(_code, RequestHelper.createFileParts(imgs),
                    mDialogFrament
                            .getDes());
        }

        final Dialog waitDialog = DialogUtil.getWaitDialog(this, "上传中...");
        waitDialog.show();
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                waitDialog.dismiss();
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful()) {
                    if (baseDTO != null && baseDTO.isSuccessful()) {
                        if (mDialogFrament != null) {
                            mDialogFrament.dismiss();
                        }
                        ToastUtil.showToast("上传成功");
                        ApiRequestData(LOADING);
                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    ToastUtil.showToast(response.code() + response.message());
                }

            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                ToastUtil.showToast("网络故障");
                waitDialog.dismiss();
            }
        });
    }


    protected class MyAdapter extends RecyclerView.Adapter {
        private static final int ITEM_TYPE_EMPTY   = 0x02;
        private static final int ITEM_TYPE_IMG     = 0x01;
        private static final int ITEM_TYPE_DEFAULT = 0x00;


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            if (viewType == ITEM_TYPE_IMG) {
                return new MyViewHolder(mInflater.inflate(R.layout.item_station_image, parent,
                        false));
            } else if (viewType == ITEM_TYPE_EMPTY) {
                return new EmptyHolder(mInflater.inflate(R.layout.item_empty_nodata_center, parent, false));
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (getItemViewType(position) == ITEM_TYPE_IMG) {
                ((MyViewHolder) holder).update(position);
            } else if (getItemViewType(position) == ITEM_TYPE_EMPTY) {
                ((EmptyHolder) holder).update(position);
            }

        }

        @Override
        public int getItemCount() {
            return dataList == null ? 0 : dataList.size();
        }

        @Override
        public int getItemViewType(int position) {
            Object data = dataList.get(position);
            if (data instanceof ImageInfo) {
                return ITEM_TYPE_IMG;
            } else if (data.equals(Constants.EMPTY_VIEW)) {
                return ITEM_TYPE_EMPTY;
            }
            return ITEM_TYPE_DEFAULT;
        }


        protected class MyViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.iv_image)
            ImageView   ivImage;
            @BindView(R.id.iv_del)
            ImageView   ivDel;
            @BindView(R.id.fl_cover)
            FrameLayout flCover;

            int position;

            public MyViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }

            public void update(int position) {
                this.position = position;
                ImageInfo data = (ImageInfo) dataList.get(position);
                loadNetImg(ivImage, data.getImgUrl());
                flCover.setVisibility(data.getIsHome() == 1 ? View.VISIBLE : View.GONE);

            }

            @OnLongClick({R.id.iv_image})
            public boolean onLongClick(View view) {
                ImageInfo data = (ImageInfo) dataList.get(position);
                switch (view.getId()) {
                    case R.id.iv_image:
                        if ((Global.user.getSetStationHome() == 1 && _type == TYPE_STATION)
                                || (Global.user.getSetDeviceHome() == 1 && _type == TYPE_DEVICE)) {
                            ApiSetCover(data.getId(), position);
                        }


                        break;
                    default:
                        break;
                }
                return true;
            }

            @OnClick({R.id.iv_image, R.id.iv_del})
            public void onClick(View view) {
                ImageInfo data = (ImageInfo) dataList.get(position);
                switch (view.getId()) {
                    case R.id.iv_image:
                        ImageGalleryActivity.show(ImageActivity.this, getUrls(),
                                position, false);
                        break;
                    case R.id.iv_del:
                        ApiDeleteImg(data.getId(), position);
                        break;
                }

            }

            private String[] getUrls() {
                String[] urls = new String[dataList.size()];
                for (int i = 0; i < dataList.size(); i++) {
                    urls[i] = ((ImageInfo) dataList.get(i)).getImgUrl();
                }
                return urls;
            }

        }

        public class EmptyHolder extends RecyclerView.ViewHolder {
            View itemView;

            public EmptyHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
            }

            public void update(int position) {

            }
        }
    }

    private void ApiSetCover(final int id, final int position) {
        DialogUtil.getConfirmDialog(this, "设为封面？", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, int which) {
                dialog.dismiss();
                final Dialog wDialog = DialogUtil.getWaitDialog(ImageActivity.this, "请等待...");
                wDialog.show();
                Call<BaseDTO> call;
                if (_type == TYPE_DEVICE) {
                    call = HxTransmitRequestHelper.getRequestApi().setDeviceCover(id);
                } else {
                    call = HxTransmitRequestHelper.getRequestApi().setStationCover(id);
                }

                call.enqueue(new Callback<BaseDTO>() {
                    @Override
                    public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                        wDialog.dismiss();
                        BaseDTO baseDTO = response.body();
                        if (response.isSuccessful() && baseDTO != null) {
                            if (baseDTO.isSuccessful()) {
                                ToastUtil.showToast("设置成功!");
                                ImageInfo data = (ImageInfo) dataList.get(position);
                                for (Object imageInfo : dataList) {
                                    ((ImageInfo) imageInfo).setIsHome(0);
                                }
                                data.setIsHome(1);
                                adapter.notifyDataSetChanged();
                            } else {
                                ToastUtil.showToast(baseDTO.getMsg());
                            }
                        } else {
                            ToastUtil.showToast("数据异常!");
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseDTO> call, Throwable t) {
                        wDialog.dismiss();
                        ToastUtil.showToast("网络异故障!");
                    }
                });
            }
        }).show();
    }

    private void ApiDeleteImg(final int id, final int position) {

        DialogUtil.getConfirmDialog(this, "确认删除图片？", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, int which) {
                dialog.dismiss();
                final Dialog wDialog = DialogUtil.getWaitDialog(ImageActivity.this, "正在删除...");
                wDialog.show();
                Call<BaseDTO> call;
                if (_type == TYPE_DEVICE) {
                    call = HxTransmitRequestHelper.getRequestApi().deleteDeviceImg(id);
                } else {
                    call = HxTransmitRequestHelper.getRequestApi().deleteStationImg(id);
                }

                call.enqueue(new Callback<BaseDTO>() {
                    @Override
                    public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                        wDialog.dismiss();
                        BaseDTO baseDTO = response.body();
                        if (response.isSuccessful() && baseDTO != null) {
                            if (baseDTO.isSuccessful()) {
                                ToastUtil.showToast("删除成功!");
                                dataList.remove(position);
                                adapter.notifyDataSetChanged();
                            } else {
                                ToastUtil.showToast(baseDTO.getMsg());
                            }
                        } else {
                            ToastUtil.showToast("数据异常!");
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseDTO> call, Throwable t) {
                        wDialog.dismiss();
                        ToastUtil.showToast("网络异故障!");
                    }
                });
            }
        }).show();


    }


    private void ApiRequestData(int status) {
        updateLoadStatus(status);
        if (_type == TYPE_STATION) {
            Call<StationImgDTO> call = HxTransmitRequestHelper.getRequestApi().getStationImg(_code);
            autoClose(call);
            call.enqueue(new Callback<StationImgDTO>() {
                @Override
                public void onResponse(Call<StationImgDTO> call, Response<StationImgDTO> response) {
                    StationImgDTO stationImgDTO = response.body();
                    if (response.isSuccessful()) {
                        if (stationImgDTO != null && stationImgDTO.isSuccessful()) {
                            updateLoadStatus(LOAD_SUCCESS);
                            dataList.clear();
                            if (stationImgDTO.getImgList() == null || stationImgDTO.getImgList()
                                    .isEmpty()) {
                                gridView.setLayoutManager(new LinearLayoutManager(ImageActivity
                                        .this,
                                        LinearLayoutManager.VERTICAL, false));
                                dataList.add(Constants.EMPTY_VIEW);

                            } else {
                                gridView.setLayoutManager(new GridLayoutManager(ImageActivity
                                        .this, 3));
                                dataList.addAll(stationImgDTO.getImgList());
                            }
                            adapter.notifyDataSetChanged();

                        } else {
                            updateLoadStatus(LOAD_FAILURE);
                        }
                    } else {
                        updateLoadStatus(LOAD_FAILURE);
                    }
                }

                @Override
                public void onFailure(Call<StationImgDTO> call, Throwable t) {
                    updateLoadStatus(LOAD_FAILURE);
                }
            });
        } else {
            Call<DeviceImgDTO> call = HxTransmitRequestHelper.getRequestApi().getDeviceImg(_code);
            autoClose(call);
            call.enqueue(new Callback<DeviceImgDTO>() {
                @Override
                public void onResponse(Call<DeviceImgDTO> call, Response<DeviceImgDTO> response) {
                    DeviceImgDTO deviceImgDTO = response.body();
                    if (response.isSuccessful()) {
                        if (deviceImgDTO != null && deviceImgDTO.isSuccessful()) {
                            updateLoadStatus(LOAD_SUCCESS);
                            dataList.clear();
                            if (deviceImgDTO.getImages() == null || deviceImgDTO.getImages().isEmpty
                                    ()) {
                                gridView.setLayoutManager(new LinearLayoutManager(ImageActivity
                                        .this,
                                        LinearLayoutManager.VERTICAL, false));
                                dataList.add(Constants.EMPTY_VIEW);

                            } else {
                                gridView.setLayoutManager(new GridLayoutManager(ImageActivity
                                        .this, 3));
                                dataList.addAll(deviceImgDTO.getImages());
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            updateLoadStatus(LOAD_FAILURE);
                        }
                    } else {
                        updateLoadStatus(LOAD_FAILURE);
                    }
                }

                @Override
                public void onFailure(Call<DeviceImgDTO> call, Throwable t) {
                    updateLoadStatus(LOAD_FAILURE);
                }
            });
        }


    }
}
